package com.lc.headline.controller;


import com.lc.headline.common.Result;
import com.lc.headline.common.ResultCodeEnum;
import com.lc.headline.pojo.NewsHeadline;
import com.lc.headline.service.NewsHeadlineService;
import com.lc.headline.service.impl.NewsHeadlineServiceImpl;
import com.lc.headline.util.JwtHelper;
import com.lc.headline.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liuchun
 */
@WebServlet("/headline/*")
public class NewsHeadlineController extends BaseController{

    private NewsHeadlineService newsHeadlineService = new NewsHeadlineServiceImpl();


    //保存修改
    protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NewsHeadline newsHeadline = WebUtil.readJson(request, NewsHeadline.class);
        newsHeadlineService.update(newsHeadline);
        Result result = Result.ok(null);
        WebUtil.writeJson(response,result);
    }

    //修改头条回显
    protected void findHeadlineByHid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int hid = Integer.parseInt(request.getParameter("hid"));
        NewsHeadline newsHeadline = newsHeadlineService.findHeadlineByHid(hid);
        Map data = new HashMap();
        data.put("headline",newsHeadline);
        WebUtil.writeJson(response,Result.ok(data));
    }

    //删除新闻头条
    protected void removeByHid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer hid = Integer.parseInt(request.getParameter("hid"));
        Result result = Result.ok(null);
        if (!newsHeadlineService.removeNews(hid)){
            result = Result.build(null, ResultCodeEnum.NOTLOGIN);
        }
        WebUtil.writeJson(response,result);
    }

    //提交发布头条
    protected void publish(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String token = request.getHeader("token");
        NewsHeadline newsHeadline = WebUtil.readJson(request, NewsHeadline.class);
        Long userUid = JwtHelper.getUserId(token);
        newsHeadline.setPublisher(userUid.intValue());
        newsHeadlineService.addNewsHeadline(newsHeadline);
        WebUtil.writeJson(response, Result.ok(null));
    }
}
